const db = uniCloud.database();
const { util, InsideErr, BaseErr } = require("utils");
const TableName = "auth-token";
const collection = db.collection(TableName);
async function getDbCache(type, appId) {
    let [err, res] = await util.awaitWrap(
        collection
            .where({
                type: type,
                appId: appId,
            })
            .limit(1)
            .get()
    );
    if (err) {
        return [new InsideErr(err), res];
    }
    let { data = [] } = res || {};
    let dataArr = Array.isArray(data) ? data : [];
    return [null, dataArr[0]];
}
// 保存 token信息
async function saveTokenInfo(info) {
    // 阿里云  表 不存在 , add  会 自动创建表
    // 腾讯/支付宝  表不存在, add 会报错
    try {
        let res = await collection.add(info);
        let docId = res.id || "";
        let docData = {
            ...info,
            _id: docId,
        };
        return [null, docData];
    } catch (error) {
        console.log("数据库添加失败...", error);
        let e = new InsideErr(error);
        return [e, false];
    }
}
// 更新 token 信息
async function updateTokenInfo(docId, newInfo) {
    try {
        // 更新
        await collection.doc(docId).update(newInfo);
        return [null, true];
    } catch (error) {
        let e = new InsideErr(error);
        return [e, false];
    }
}

// 获取某个文档的数据
async function getDocData(docId = "") {
    try {
        let res = await collection.doc(docId).get();
        let { data } = res || {};
        let arr = Array.isArray(data) ? data : [];
        let docData = arr[0];
        if (util.nilValue(docData)) {
            return [new BaseErr(-5001, "文档数据不存在"), null];
        }
        return [null, docData];
    } catch (error) {
        let e = new InsideErr(error);
        return [e, false];
    }
}

// 使用事务 更新 数据
async function transactionUpdate(docId, update) {
    const transaction = await db.startTransaction();
    try {
        const tokenCollection = transaction.collection(TableName);
        // 更新
        let res = await tokenCollection.doc(docId).update(update);
        await transaction.commit();
        return [undefined, res];
    } catch (error) {
        console.log("事务 更新失败 ", error);
        await transaction.rollback();
        return [new InsideErr(error), null];
    }
}

module.exports = {
    getDbCache,
    saveTokenInfo,
    updateTokenInfo,
    getDocData,
    transactionUpdate,
};
